package com.training.service;

import com.training.entity.Information;
import com.training.mapper.InformationMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
public class InformationService {

    private final InformationMapper informationMapper;

    @Value("${file.upload-base-dir}")
    private String uploadBaseDir;

    public InformationService(InformationMapper informationMapper) {
        this.informationMapper = informationMapper;
    }

    private String saveFile(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return "/images/default-info.png"; // 返回默认图片路径
        }
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path uploadPath = Paths.get(uploadBaseDir, "info_images");
        Files.createDirectories(uploadPath);
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);
        return "/info_images/" + fileName;
    }

    public void createInformation(Information information, MultipartFile imageFile) throws IOException {
        if (information.getInfoTitle() == null || information.getInfoTitle().trim().isEmpty() ||
                information.getInfoMain() == null || information.getInfoMain().trim().isEmpty()) {
            throw new IllegalArgumentException("标题和内容不能为空。");
        }
        String imagePath = saveFile(imageFile);
        information.setInfoImage(imagePath);
        informationMapper.insert(information);
    }

    public void updateInformation(Information information, MultipartFile imageFile) throws IOException {
        if (information.getInfoTitle() == null || information.getInfoTitle().trim().isEmpty() ||
                information.getInfoMain() == null || information.getInfoMain().trim().isEmpty()) {
            throw new IllegalArgumentException("标题和内容不能为空。");
        }
        if (imageFile != null && !imageFile.isEmpty()) {
            String imagePath = saveFile(imageFile);
            information.setInfoImage(imagePath);
        }
        informationMapper.update(information);
    }

    public void deleteInformation(Long id, Long teacherId) {
        informationMapper.delete(id, teacherId);
    }

    public Information getInformationById(Long id) {
        return informationMapper.findById(id);
    }

    public List<Information> getAllInformation(String keyword) {
        return informationMapper.findAll(keyword);
    }

    public List<Information> getInformationByTeacher(Long teacherId, String keyword) {
        return informationMapper.findByTeacherId(teacherId, keyword);
    }
}